package com.zheng.business.web.service;

import com.zheng.business.common.constant.BusinessConstant;
import com.zheng.business.common.constant.BusinessResult;
import com.zheng.business.common.constant.BusinessResultConstant;
import com.zheng.business.dao.model.*;
import com.zheng.business.rpc.api.BusinessAgentAmountStatisticsService;
import com.zheng.business.rpc.api.BusinessAgentBillStatisticsLogService;
import com.zheng.business.rpc.api.BusinessAgentBillStatisticsService;
import com.zheng.business.rpc.api.BusinessApiService;
import com.zheng.business.web.util.StatisticsUtil;
import com.zheng.common.constant.Constant;
import com.zheng.common.util.StringUtil;
import com.zheng.upms.dao.model.UpmsAgent;
import com.zheng.upms.dao.model.UpmsAgentExample;
import com.zheng.upms.rpc.api.UpmsApiService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;

/**
 * @author lvg EMIAL：<a href="mailto:weiguo.liang@gh-ca.com">weiguo.liang@gh-ca.com</a> <br>
 * @version 1.0 <br>
 * @Company: GH-CA<br>
 * @ClassName: BusinessAgentHttpTaskService <br>
 * @Description: TODO <br>
 * @date 2019/8/8 17:29<br>
 **/
@Service
public class BusinessAgentHttpTaskService {

    @Autowired
    private BusinessApiService businessApiService;

    @Autowired
    private UpmsApiService upmsApiService;

    @Autowired
    BusinessAgentAmountStatisticsService businessAgentAmountStatisticsService;

    @Autowired
    BusinessAgentBillStatisticsService businessAgentBillStatisticsService;

    @Autowired
    BusinessAgentBillStatisticsLogService businessAgentBillStatisticsLogService;

    /**
     *
     * @param dateStr
     * @param dateType
     * @return
     */
    public BusinessResult statisticsAgentAmountByDateTypeAndDate(String dateStr, BusinessConstant.StatisticsDateType dateType) {
        Map<String,Object> params = StatisticsUtil.getStatisticsParams(dateStr,dateType);
        Date currentDate = new Date();


        UpmsAgentExample upmsAgentExample = new UpmsAgentExample();
        upmsAgentExample.createCriteria().andFlagEqualTo(Constant.CONST_FLAG_NORMAL);

        //代理集合
        List<UpmsAgent> agents = upmsApiService.selectUpmsAgentByExample(upmsAgentExample);

        //统计实例集合
        List<BusinessAgentAmountStatistics> statisticsList = new ArrayList<BusinessAgentAmountStatistics>();

        //代理统计map
        Map<Integer, BusinessAgentAmountStatistics> amountMap = new HashMap<Integer, BusinessAgentAmountStatistics>();

        for(UpmsAgent agent : agents){
            BusinessAgentAmountStatistics statistics = new BusinessAgentAmountStatistics();
            statistics.setAgentId(agent.getId());
            statistics.setAmount(new BigDecimal(0));
            statistics.setCreateTime(currentDate);
            statistics.setType(BusinessConstant.StatisticsDateType.DAY.getValue());
            statistics.setUnit(params.get("unitDateStr").toString());
            amountMap.put(agent.getId(),statistics);
            statisticsList.add(statistics);
        }

        //雨伞订单时间段统计结果
        List<Map<String,Object>> orderResultList = businessApiService.getAgentOrderAmountByTimeSlot((Date)params.get("beginTime"),(Date)params.get("endTime"));
        for(Map<String,Object> map : orderResultList){
            Integer agentId = StringUtil.getInteger(map.get("agentId"));
            String amount = StringUtil.getString(map.get("sumAmount"));
            if(agentId!=null && StringUtils.isNotBlank(amount)){
                BusinessAgentAmountStatistics statistics = amountMap.get(agentId);
                if(statistics!=null){
                    statistics.setAmount(statistics.getAmount().subtract(new BigDecimal(amount)));
                }
            }
        }
        //时长卡订单时间段统计结果
        List<Map<String,Object>> timecardResultList = businessApiService.getAgentTimecardAmountByTimeSlot((Date)params.get("beginTime"),(Date)params.get("endTime"));
        for(Map<String,Object> map : timecardResultList){
            Integer agentId = StringUtil.getInteger(map.get("agentId"));
            String amount = StringUtil.getString(map.get("sumAmount"));
            if(agentId!=null && StringUtils.isNotBlank(amount)){
                BusinessAgentAmountStatistics statistics = amountMap.get(agentId);
                if(statistics!=null){
                    statistics.setAmount(statistics.getAmount().subtract(new BigDecimal(amount)));
                }
            }
        }
        //保存统计结果
        for(BusinessAgentAmountStatistics statistics : statisticsList){
            businessAgentAmountStatisticsService.insertSelective(statistics);
        }

        return new BusinessResult(BusinessResultConstant.SUCCESS,null);
    }


    /**
     * 统计代理账单 一月出账一次，固定
     * @param dateStr
     * @return
     */
    public BusinessResult statisticsAgentAmountBill(String dateStr) {
;        Map<String,Object> params = StatisticsUtil.getStatisticsParams(dateStr, BusinessConstant.StatisticsDateType.MONTH);
        Date currentDate = new Date();


        UpmsAgentExample upmsAgentExample = new UpmsAgentExample();
        upmsAgentExample.createCriteria().andFlagEqualTo(Constant.CONST_FLAG_NORMAL);

        //代理集合
        List<UpmsAgent> agents = upmsApiService.selectUpmsAgentByExample(upmsAgentExample);

        //代理统计map
        Map<Integer, BigDecimal> amountMap = new HashMap<Integer, BigDecimal>();

        String month = params.get("unitDateStr").toString();


        BusinessAgentBillStatisticsLogExample logExample = new BusinessAgentBillStatisticsLogExample();
        BusinessAgentBillStatisticsLogExample.Criteria logExampleCriteria = logExample.createCriteria();
        logExampleCriteria.andCreateMonthEqualTo(month);
        int c = businessAgentBillStatisticsLogService.countByExample(logExample);
        if (c == 0) {    // 如果存在 log 说明复制过历史账单，则不再重复复制
            int count = businessApiService.copyTimecard2HistroyByTimeSlot((Date)params.get("beginTime"),(Date)params.get("endTime"),month);

            int count1 = businessApiService.copyUmbrellaOrder2HistroyByTimeSlot((Date)params.get("beginTime"),(Date)params.get("endTime"),month);


            for(UpmsAgent agent : agents){
                amountMap.put(agent.getId(),new BigDecimal(0));
            }

            //雨伞订单时间段统计结果
            List<Map<String,Object>> orderResultList = businessApiService.getAgentUmbrellaOrderBillAmountByTime(month);
            for(Map<String,Object> map : orderResultList){
                Integer agentId = StringUtil.getInteger(map.get("agentId"));
                String amount = StringUtil.getString(map.get("sumAmount"));
                if(agentId!=null && StringUtils.isNotBlank(amount)){
                    BigDecimal a = amountMap.get(agentId);
                    if(a!=null){
                        amountMap.put(agentId,a.add(new BigDecimal(amount)));
                    }
                }
            }
            //时长卡订单时间段统计结果
            List<Map<String,Object>> timecardResultList = businessApiService.getAgentTimecardOrderBillAmountByTime(month);
            for(Map<String,Object> map : timecardResultList){
                Integer agentId = StringUtil.getInteger(map.get("agentId"));
                String amount = StringUtil.getString(map.get("sumAmount"));
                if(agentId!=null && StringUtils.isNotBlank(amount)){
                    BigDecimal a = amountMap.get(agentId);
                    if(a!=null){
                        amountMap.put(agentId,a.add(new BigDecimal(amount)));
                    }
                }
            }

            for(UpmsAgent agent : agents){

                this.statisticsParentAgentAmount(agent.getId(),null,amountMap.get(agent.getId()),
                        currentDate,params);

            }
        }
        return new BusinessResult(BusinessResultConstant.SUCCESS,null);
    }

    /**
     * 计算子代理扣除的金额给父代理
     * @param agentId 父代理Id
     * @param subAgentId 子代理
     * @param amount 子代理扣除的金额
     * @param currentDate 当前时间
     * @param params 过滤参数map
     */
    private void statisticsParentAgentAmount(Integer agentId,String subAgentId,BigDecimal amount,Date currentDate,Map<String,Object> params){

        if(agentId == null) return;

        BusinessAgentBillStatisticsLogExample logExample = new BusinessAgentBillStatisticsLogExample();
        BusinessAgentBillStatisticsLogExample.Criteria logExampleCriteria = logExample.createCriteria();
        logExampleCriteria.andAgentIdEqualTo(agentId);
        if(subAgentId != null){
            logExampleCriteria.andSubAgentIdEqualTo(subAgentId);
        }else{
            logExampleCriteria.andSubAgentIdIsNull();
        }
        logExampleCriteria.andCreateMonthEqualTo(params.get("unitDateStr").toString());
        BusinessAgentBillStatisticsLog statisticsLog = businessAgentBillStatisticsLogService.selectFirstByExample(logExample);
        if (statisticsLog != null) { //如果已生成过该月的统计则不再生成
            return;
        }
        UpmsAgent agent = upmsApiService.selectUpmsAgentByPrimaryKey(agentId);
        if(agent != null){ // 存在父级代理
            BusinessAgentBillStatisticsExample example = new BusinessAgentBillStatisticsExample();
            BusinessAgentBillStatisticsExample.Criteria criteria = example.createCriteria();
            criteria.andAgentIdEqualTo(agent.getId());

            BusinessAgentBillStatisticsLog log = new BusinessAgentBillStatisticsLog();

            BusinessAgentBillStatistics statistics = businessAgentBillStatisticsService.selectFirstByExample(example);
            if(statistics == null){
                statistics = new BusinessAgentBillStatistics();
                statistics.setAmountRateTotal(new BigDecimal(0));
                statistics.setAmountTotal(new BigDecimal(0));
                statistics.setAgentId(agentId);
                statistics.setAmountRemainder(new BigDecimal(0));
                statistics.setCreateTime(currentDate);
                statistics.setUpdateTime(currentDate);
            }

            log.setAmountRateTotalBefore(statistics.getAmountRateTotal());
            log.setAmountRemainderBefore(statistics.getAmountRemainder());
            log.setAmountTotalBefore(statistics.getAmountTotal());

            //当前代理总费用 + 时间段总费用
            statistics.setAmountTotal(
                    statistics.getAmountTotal().add(amount)
            );

            BigDecimal prateTotal = amount.multiply(agent.getRate().divide(new BigDecimal(100)));
            //当前代理扣后总费用 + 时间段总费用 - 时间段总费用*扣取比例
            statistics.setAmountRateTotal(
                    statistics.getAmountRateTotal().add(
                            amount.subtract(prateTotal)
                    )
            );
            statistics.setAmountRemainder(statistics.getAmountRemainder().add(amount.subtract(prateTotal)));

            log.setAmountRateTotalAlter(statistics.getAmountRateTotal());
            log.setAmountRemainderAlter(statistics.getAmountRemainder());
            log.setAmountTotalAlter(statistics.getAmountTotal());
            log.setAmount(amount);
            log.setRate(agent.getRate());
            log.setRateAmount(prateTotal);
            log.setAmountAlter(amount.subtract(prateTotal));
            log.setAgentId(agentId);
            log.setSubAgentId(subAgentId);
            log.setCreateMonth(params.get("unitDateStr").toString());
            log.setCreateTime(currentDate);

            if (statistics.getId() == null) {
                businessAgentBillStatisticsService.insertSelective(statistics);
            } else {
                businessAgentBillStatisticsService.updateByPrimaryKeySelective(statistics);
            }

            businessAgentBillStatisticsLogService.insertSelective(log);

            statisticsParentAgentAmount(agent.getPid(),subAgentId != null ? (subAgentId + "," + agent.getId()) : agent.getId().toString(),prateTotal,currentDate,params);
        }
    }
}
